import { ref } from 'vue'
import request from '@/api/index'
import { xmloading, xmtoast } from '@/utils/public';
import { defineStore } from 'pinia';
import { userStore } from "./user";
import { LocationQueryValue } from 'vue-router';

interface betsListForm {
  allPrice:number | string // 总押注金额
  poolId:number // 羊id
  price:number | string // 当前用户押注金额
  rankList:Array<any> // 押注前三
  magn:number // 倍率
}
interface stakeForm {
  type:number
  integral:number
}
interface GameResultForm {
  gameNum:number
  poolId:number
  gameResult:number
  rewardPrice:number
  winner:number
}
interface specialPool {
  poolId:number,
  num:number
}
let getTicket_num = 0
let timeout = 0
let outcomeTimeout = 0
let newSpecialPool = [] as Array<specialPool>
export const controlStore = defineStore('controller', {
  state: () => ({
    user_id:'' as LocationQueryValue | LocationQueryValue[],
    gameNum:0, // 当前游戏局数
    round:0, // 回合数
    timekeepingTime:0, // 倒计时时间
    playState:false as Boolean, // 羊运动状态
    hastenSet:false as Boolean, // 羊运动状态 是否加速
    outcome:0, // 中奖结果
    cattleLeft:null as null | number, // 捕获该位置的羊
    cattleLeftArr:[] as Array<any>, // 中间羊存在于可视范围内的
    stakeMaxList:[] as Array<any>, // 今天Top3
    cattleArr1:[] as Array<any>, // 第一排羊
    cattleArr2:[] as Array<any>, // 第二排羊
    hasStakeList:[] as Array<betsListForm>, // 押注列表
    storageHasStakeList:[] as Array<betsListForm>, // 押注列表原始数据
    specialPool:[] as Array<specialPool>, // 多少局未出
    ticketTop:0, // 卡券起点
    ticketLeft:0, // 卡券起点
    ticketBox:ref(), // 卡券起点dom
    showWinner:false, // 押注结果弹窗
    gameRoomId:0,// 游戏房间ID
    rong_token:'', // 用户融云token
    stakeType:[] as Array<stakeForm>, // 押注列表
    GameResult:{
      winner:0,
      gameNum:0,
      poolId:0,
      gameResult:0,
      rewardPrice:0
    } as GameResultForm, // 中奖的结果
    winList:[] as Array<any>,
    betsStatus:false, // 是否押注过 未押注过不执行清除接口
  }),
  actions: {
    // 羊 开始运动
    getPlayState(type:Boolean = false) {
      this.playState = type
      if(type) {
        // this.cattleLeftArr = []
        this.cattleLeft = null
      }
      // console.log('羊 开始运动 cattleLeft', this.cattleLeft);
    },
    // 追加存在屏幕中的羊
    getCattleLeftArr(left:number){
      // this.cattleLeftArr.push(left)
      // console.log('追加存在屏幕中的羊 this.round', this.round);
      if(!this.cattleLeft) {
        this.cattleLeft = left
      }
      // console.log('追加存在屏幕中的羊',this.cattleLeft);
    },
    // 卡券启始位置
    ticketLocation() {
      const { top,left } = this.ticketBox.getBoundingClientRect()
      this.ticketTop = top
      this.ticketLeft = left
    },
    // 获取游戏信息
    async getGameInfo() {
      const res = await request.gameInfo()
      const {
        hasStakeList=[], stakeType=[], stakeMaxList=[], winner=0,
        gameRoomId, rong_token, gameNum=0, round=0, specialPool=[]} = res.data
      this.hasStakeList = hasStakeList
      this.storageHasStakeList = hasStakeList.map((res:any)=>{
        const { poolId, magn, name } = res
        return {
          poolId,
          price:0,
          allPrice:0,
          magn,
          name,
          rankList:[]
        }
      })
      const cattleArr1 = hasStakeList.filter((res:any,index:number)=> index < 4)
      const cattleArr2 = hasStakeList.filter((res:any,index:number)=> index > 3)
      this.cattleArr1 = [...cattleArr1,...cattleArr1]
      this.cattleArr2 = [...cattleArr2,...cattleArr2]
      this.outcome = winner
      if(winner) {
        this.GameResult.winner = winner
      }
      this.gameNum = gameNum
      this.round = round
      this.timekeepingTime = 21 - round
      this.stakeType = stakeType
      this.stakeMaxList = stakeMaxList
      this.specialPool = specialPool
      return {
        rong_token,
        gameRoomId
      }
    },
    async getMessages(messages:any = {}) {
      for(let item of messages) {
        const {  content={} } = item
        const { data={}, k=0 } = content
        // 用户押注
        if(k == 60113) {
          const { hasStakeList=[], stakeMaxList=[], gameNum, userId } = data
          if(this.gameNum != gameNum) return xmtoast('回合异常')
          const list = hasStakeList.map((res:any)=>{
            const query = res
            if(userId != this.user_id) {
              const poolObj = this.hasStakeList.find(obj=> res.poolId == obj.poolId)
              query.price = poolObj?.price
            }
            return query
          })
          this.hasStakeList = list
          this.stakeMaxList = stakeMaxList
        }
        // 回合信息
        if(k == 60114) {
          // console.log('cattleLeft --- ', this.cattleLeft);
          const { round, gameNum, winner=0, specialPool=[] } = data
          if(this.gameNum != gameNum) {
            // 场次更新 初始化押注区
            this.hasStakeList = JSON.parse(JSON.stringify(this.storageHasStakeList))
          }
          this.gameNum = gameNum
          this.round = round
          this.timekeepingTime = 21 - round
          if(round == 1) {
            this.specialPool = specialPool
            // this.cattleLeftArr = []
            this.cattleLeft = 0
          }
          if(round >= 1 && round < 25) {
            if(!this.playState) {
              this.getPlayState(true) // 开始运动
            }
          }
          if(round == 5) {
            this.showWinner = false
            this.outcome = 0
          }
          if(round == 6) {
            // 清楚结果记录
            this.GameResult = {
              winner:0,
              gameNum:0,
              poolId:0,
              gameResult:0,
              rewardPrice:0
            }
          }
          // 羊开始加速运动
          if(round >= 22 && round < 26) {
            if(!this.hastenSet && this.cattleLeft == null) this.hastenSet = true
          }

          // 获取用户中奖结果
          if(round >= 25 && winner && !this.GameResult.gameNum) {
            if(winner) {
              this.getGameResult()
            }
          }
          if(round < 26 && this.cattleLeft != null) this.cattleLeft = null
          // 羊停止运动
          if(round >= 26 && winner > 0) {
            this.hastenSet = false
            outcomeTimeout = setTimeout(() => {
              this.getPlayState(false)
              this.outcome = winner
              this.GameResult['winner'] = winner
              clearTimeout(outcomeTimeout)
            }, 200);
          }
          if(round == 27) {
            // 羊的停止 于 捕捉图切换
            // if(this.cattleLeftArr.length > 0) {
            //   this.getCattleLeft()
            // } else {
            //   xmtoast('未捕捉到屏幕中的羊')
            // }
            // 处理中奖记录
            const winList = JSON.parse(JSON.stringify(this.winList))
            if(winList.length == 56) {
              winList.pop()
            }
            winList.unshift({
              poolId:winner,
              magn:this.hasStakeList.find(res=>res.poolId == winner)?.magn || ''
            })
            this.winList = winList
            timeout = setTimeout(async()=>{
              // 更新券数
              userStore().setWallet({
                ticket_num:getTicket_num
              })
              if(!this.GameResult.gameNum) {
                // console.log('this.GameResult.gameNum 1/', this.GameResult.gameNum);
                await this.getGameResult()
                // console.log('this.GameResult.gameNum 2/', this.GameResult.gameNum);
              }
              this.showWinner = true  
              clearTimeout(timeout)
            },500)
          }
          // console.log('回合信息 data', round, data);
        }
      }
    },
    async getGameResult() {
      await request.getGameResult({
        gameNum:this.gameNum
      }).then(obj=>{
        const { ticket_num=0 } = obj?.data || {}
        const data = obj.data || {
          gameNum:0,
          poolId:0,
          gameResult:0,
          rewardPrice:0,
          winner:this.outcome
        }
        getTicket_num = ticket_num
        this.GameResult = data
      }).catch(()=>{

      })
    }
  },
})